#!/usr/bin/python
#coding:utf-8

import threading
import time
import redis
import json
import sys

sys.path.append("../clicent")
sys.path.append('../..')
from python_post_main import main
from config.tdm_config import *

reload(sys)
sys.setdefaultencoding('utf8')

server_sleep = 300
server_delay = 0.01

class multi_server_post(threading.Thread):
    def __init__(self, city, jxd, server):
        threading.Thread.__init__(self)
        self.city = city
        self.jxd = jxd
        self.server = server
        self.thread_stop = False
        #print 'int thread for', self.server

    def run(self):
        while not self.thread_stop:
            #print 'run thread for', self.server
            ret = main(self.server)
            ret_json = json.loads(ret)

            if ret_json.get('result') == 1:
                print 'Time:%s city:%s jxd:%s server:%s OK' % \
                        (time.ctime(), self.city, self.jxd, self.server)
            else:
                print 'Time:%s city:%s jxd:%s server:%s error:%s' % \
                        (time.ctime(), self.city, self.jxd, self.server, ret_json.get('err_msg'))

            time.sleep(server_sleep)

    def stop(self):
        self.thread_stop = True

def multi_server_start():
    multi_thread_list = []

    r = redis.Redis(host='127.0.0.1', db=1)
    server_list = r.hgetall(tdm_redis_key_server)
    for city_jxd_serv, ipaddr in server_list.items():
        city, jxd, server = city_jxd_serv.split('_')
        multi_thread_list.append(multi_server_post(city, jxd, server))

    for serv_thread in multi_thread_list:
        serv_thread.start()
        time.sleep(server_delay)

    for serv_thread in multi_thread_list:
        serv_thread.join()

    return

if __name__ == '__main__':
    multi_server_start()
